package com.filesearcher;

import java.awt.Color;

public class MemoryThread extends Thread
{
	private static final long  MEGABYTE = 1024L * 1024L;
	
	public MemoryThread() 
	{		
		super.setName( "MemoryThread" );
		this.setPriority( Thread.MIN_PRIORITY );
	}
	
	public void run()
	{
		while (true)
		{
			long usedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
			String used = Double.toString( bytesToMeg( usedMem ) );

			//String free =  Double.toString( bytesToMeg( Runtime.getRuntime().freeMemory() ) );
			String total = Double.toString( bytesToMeg( Runtime.getRuntime().totalMemory() ) );
			String max = Double.toString( bytesToMeg( Runtime.getRuntime().maxMemory() ) );
			GrepSearchUI.freeMemoryLabel.setText( used + " MB" + " / " + max + " MB" );

			if ( Runtime.getRuntime().freeMemory() < 100000 )
				GrepSearchUI.freeMemoryLabel.setForeground( Color.RED );
			else
				GrepSearchUI.freeMemoryLabel.setForeground( new Color( 0, 128, 0 ) );

			try 
			{
				Thread.sleep(500);
			}
			catch (InterruptedException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private static double bytesToMeg( long bytes )
	{
		double d = Double.parseDouble( Long.toString(bytes));
		
		double newD = d / MEGABYTE;
		
		return Math.round( newD * 100.0 ) / 100.0;
	}
}
